/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-09-01 12:02:15
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-09-02 20:08:30
 * @FilePath: /0901/sem_cp/main.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include "RingQueue.hpp"
#include <pthread.h>
#include <unistd.h>
#include "task.hpp"
// #include<mutex>

using namespace std;

struct ThreadData
{
    ThreadData(string name = "default")
        :_rq(nullptr)
        ,_threadname(name)
    {}

    RingQueue<Task> *_rq;
    std::string _threadname;
};

void *Consumer(void *args)
{
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        // 1、消费数据
        Task t;
        td->_rq->Pop(&t);
        // cout << "pthread: " << pthread_self() << "  Consumer get a data, data is " << data << endl;
        sleep(1);

        // 2、处理数据
        // usleep(1000);
        t.Run();
        cout << td->_threadname << "  Consumer get a task, task is " << t.GetTask() << "  result:  " << t.GetResult() << endl;

    }

    return nullptr;
}

void *Productor(void *args)
{

    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    int len = opers.size();
    while (true)
    {
        // 1、获取数据
        int data1 = rand() % 10000 + 1;
        usleep(1000);
        int data2 = rand() % 10000 + 1;
        Task t(data1, data2, opers[rand()%len]);

        // 2、生产数据
        td->_rq->Push(t);
        // cout << "pthread: " << pthread_self() << "  Productor data done, data is " << data << endl;
        cout << td->_threadname << "  Productor task done, task is " << t.GetTask() << endl;

        sleep(1);
    }

    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>(10);
    pthread_t c[5], p[3];
    for (size_t i = 0; i < 5; i++)
    {
        ThreadData *td = new ThreadData("Consumer-" + to_string(i));
        td->_rq = rq;
        pthread_create(&(c[i]), nullptr, Consumer, td);
    }
    for (size_t i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData("Productor-" + to_string(i));
        td->_rq = rq;
        pthread_create(&(p[i]), nullptr, Productor, td);
    }

    for (size_t i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (size_t i = 0; i < 3; i++)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}